// pages/product/product.js
import {Product} from "product-model.js";
import { Cart } from "../cart/cart-model";

var product = new Product();
var cart = new Cart();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:1,
    countsArray:[1,2,3,4,5,6,7,8,9,10],
    productCounts:1,
    productDetail:['商品详情','产品参数','售后保障'],
    currentTabsIndex:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options.id);
    var id = options.id;
    this.data.id = id;
    this._loadDatas();
  },


  _loadDatas:function(){
    var that = this;    
    product.getProductInfo(this.data.id,function(data){
      // console.log(data);
      that.data.product = data;
      that.setData({
        "product":data
      });
    });

    var res = cart.getCartDataFromLocal();
    var cartCount = 0;
    for(var key in res){
      cartCount += res[key].counts
    }
    // console.log(cartCount);
    this.data.cartCount = cartCount;
    that.setData({
      "cartCount":cartCount
    });
  },

  // 更改商品数量
  bindPickerChange:function(data){
    // console.log(data);
    var key = data.detail.value;
    this.data.productCounts = this.data.countsArray[key];
    this.setData({
        "productCounts":this.data.productCounts
    });
  },

  onAddingToCartTap:function(res){
    var tempObj = {};
    var keys = ['id','name','main_img_url','price'];
    // console.log(this.data.product);
    for(var key in this.data.product){
      if(keys.indexOf(key) >= 0){
        tempObj[key] = this.data.product[key];
      }
    }
    // console.log(tempObj);
    cart.addCart(tempObj,this.data.productCounts);
    var cartCount = this.data.productCounts + this.data.cartCount;
    this.setData({
      "cartCount":cartCount
    });
  },

  // 选项卡
  onTabItemtap:function(event){    
    var index = product.getDataSet(event,'index');
    // console.log(index);
    this.setData({
      "currentTabsIndex":index
    });
  },

  onCart:function(event){
    console.log(event);
    wx.switchTab({
      url:"/pages/cart/cart"
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})